import { useAuthStore } from "@/store/auth"
import { useViewRoutesStore } from "@/store/viewRoutes"
import { getMenuUser } from "@/api/auth/menu"
import type { RouteComponent, RouteRecordRaw } from "vue-router"
import { defaultRoutes } from '@/router/modules/defaultRoutes'
import { dynamicRoutes } from '@/router/modules/dynamicRoutes'
import { router } from '@/router'

/**
 * 获取src/views目录下所有的.vue文件，并排除components中的文件
 */
const modules: Record<string, RouteComponent> = import.meta.glob(['@/views/**/*.vue', '!@/views/**/components/*.vue'])
// console.log('modules', modules);
const viewsModules: Record<string, RouteComponent> = Object.keys(modules).reduce((preObj, currKey) => {
  const path = currKey.replace(/\/src\/views|..\/views/, '')
  // console.log('path', path, modules[currKey]);
  // key是变量，必须用中括号
  return Object.assign(preObj, { [path]: modules[currKey] })
}, {})
// console.log('viewsModules', viewsModules);

/**
 * 获取相对路径路由模块
 * 将 key 本地路由组件路径 '/src/views' 或 '../views' 替换成''
 */
export async function initBackEndRoutes() {
  const authStore = useAuthStore()
  // 判断是登录过
  if (!authStore.accessToken) return false

  // 请求接口获取拥有的权限菜单
  const { data } = await getMenuUser()
  // console.log('请求接口获取拥有的权限菜单', data);
  const { userInfo, menuList, buttonList } = data

  authStore.setButtonList(buttonList)
  authStore.setMenuList(menuList)
  authStore.setUserInfo(userInfo)
  console.log('menuList', menuList)

  // 3. 返回已转换后的动态路由对象数组
  const targetRoutes = dynamicImportComponent(menuList)
  // console.log('targetRoutes', targetRoutes);

  // 将目标路由替换
  dynamicRoutes[0].children = targetRoutes
  // console.log('allRoutes', allRoutes);

  // 4. 添加动态路由
  addRouteHandle()

  // 5. 将动态路由数组通过pinia保存
  setDynamicRoutes()

  // 6. 将要缓存的路由name收集后保存到pinia
  setCacheRouteNames()
}

/**
 * 将后端响应的路由数组中的component 字符串属性值，替换为动态导入组件
 * @param dynamicRoutes 动态路由
 */
export function dynamicImportComponent(dynamicRoutes: RouteRecordRaw[]): RouteRecordRaw[] {
  if (!dynamicRoutes || dynamicRoutes.length <= 0) return []
  return dynamicRoutes.map((route) => {
    const { component } = route
    // console.log('component', component);
    if (component) route.component = viewsModules[`${component}`] || viewsModules[`/${component}`]
    route.children && dynamicImportComponent(route.children)
    return route
  })
}

/**
 * 动态添加路由对象
 */
export function addRouteHandle() {
  // 将默认路由401,404权限路由合并，防止在layout布局重渲染，不然会出现401,404页面全屏显示
  const layoutRouteChildren = [...dynamicRoutes[0].children || [], ...defaultRoutes]
  // console.log('layoutRouteChildren', layoutRouteChildren);
  dynamicRoutes[0].children = layoutRouteChildren
  // console.log('dynamicRoutes', dynamicRoutes);
  // 添加动态路由
  dynamicRoutes.forEach((route) => {
    router.addRoute(route)
  })
}

/**
 * 动态路由保存到pinia
 */
function setDynamicRoutes() {
  const authStore = useAuthStore()
  authStore.setMenuList(dynamicRoutes[0].children || [])
}

/**
 * 将要缓存的路由name存在到pinia
 */
function setCacheRouteNames() {
  // 存储缓存路由的name
  const cacheRouteNames: string[] = []

  const _getNames = (route: RouteRecordRaw) => {
    // 获取缓存路由的name
    if (route.meta?.cache && route.name) {
      cacheRouteNames.push(<string>route.name)
    } else {
      // 有子路由，则递归获取name值
      if (route.children && route.children.length > 0) {
        route.children.forEach(item => _getNames(item))
      }
    }
  }

  // 调用上面递归方法
  _getNames(dynamicRoutes[0])
  console.log('cacheRouteNames', cacheRouteNames);

  const viewRoutesStore = useViewRoutesStore()
  viewRoutesStore.setcacheRouteNames(cacheRouteNames)
}